package com.example.myshopping3.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.myshopping3.mapper.BookMapper;
import com.example.myshopping3.model.Book;
import com.example.myshopping3.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 缓存键常量
    private static final String ALL_BOOKS_KEY = "books:all";
    private static final String BOOK_KEY_PREFIX = "book:";
    private static final long EXPIRATION_MINUTES = 30; // 缓存过期时间

    @Override
    public List<Book> list() {
        // 1. 尝试从缓存获取
        List<Book> books = (List<Book>) redisTemplate.opsForValue().get(ALL_BOOKS_KEY);

        if (books != null) {
            return books;
        }

        // 2. 缓存未命中，查询数据库
        books = super.list();

        // 3. 存入缓存并设置过期时间
        if (books != null && !books.isEmpty()) {
            redisTemplate.opsForValue().set(
                    ALL_BOOKS_KEY,
                    books,
                    EXPIRATION_MINUTES,
                    TimeUnit.MINUTES
            );
        }

        return books;
    }

    @Override
    public Book getById(Serializable id) {
        String key = BOOK_KEY_PREFIX + id;

        // 1. 尝试从缓存获取
        Book book = (Book) redisTemplate.opsForValue().get(key);

        if (book != null) {
            return book;
        }

        // 2. 缓存未命中，查询数据库
        book = super.getById(id);

        // 3. 存入缓存
        if (book != null) {
            redisTemplate.opsForValue().set(
                    key,
                    book,
                    EXPIRATION_MINUTES,
                    TimeUnit.MINUTES
            );
        }

        return book;
    }
    /**
     * 实现缓存清除逻辑
     *
     * @param bookId
     */
    @Override
    public void clearBookCache(Long bookId) {
        // 清除单个图书缓存
        redisTemplate.delete(BOOK_KEY_PREFIX + bookId);

        // 清除所有图书列表缓存（因为列表可能包含该图书）
        redisTemplate.delete(ALL_BOOKS_KEY);
    }


    /**
     * 获取所有图书信息
     * @return
     */
    @Override
    public List<Book> getAllBooks() {
        return null;
    }

    /**
     * 获取一条图书信息
     * @param id
     * @return
     */
    @Override
    public Book getBookById(Integer id) {
        return null;
    }


}
